import React, { useState } from 'react';
import { 
  Table, 
  Button, 
  Input, 
  Space, 
  message, 
  Popconfirm
} from 'antd';
import { 
  SearchOutlined,
  PlusOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import CommonFormModal from '../../components/CommonFormModal';
import { useFormModal } from '../../hooks/useFormModal';
import { permissionFormConfig } from '../../utils/formConfigs';

interface Role {
  id: string;
  roleCode: string;
  roleName: string;
  creator: string;
  createTime: string;
  modifier: string;
  modifyTime: string;
}

const Permission: React.FC = () => {
  const [roles, setRoles] = useState<Role[]>([
    {
      id: '1',
      roleCode: '1020',
      roleName: '管理员',
      creator: 'admin',
      createTime: '2021-01-22',
      modifier: 'admin',
      modifyTime: '2020-10-22'
    },
    {
      id: '2',
      roleCode: '1021',
      roleName: '管理员',
      creator: 'admin',
      createTime: '2021-01-22',
      modifier: 'zhangsan',
      modifyTime: '2020-10-22'
    },
    {
      id: '3',
      roleCode: '1022',
      roleName: '仓储经理',
      creator: 'admin',
      createTime: '2021-01-22',
      modifier: 'admin',
      modifyTime: '2020-10-22'
    },
    {
      id: '4',
      roleCode: '1023',
      roleName: '操作员',
      creator: 'admin',
      createTime: '2021-01-22',
      modifier: 'admin2',
      modifyTime: '2020-10-22'
    },
    {
      id: '5',
      roleCode: '1024',
      roleName: '办公室',
      creator: 'admin',
      createTime: '2021-01-19',
      modifier: 'admin1',
      modifyTime: '2020-10-22'
    }
  ]);

  const [searchText, setSearchText] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 使用通用表单Hook
  const {
    visible,
    isAddMode,
    currentRecord,
    loading,
    openAddModal,
    openEditModal,
    closeModal,
  } = useFormModal<Role>();

  const columns: ColumnsType<Role> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_, __, index) => (currentPage - 1) * pageSize + index + 1,
    },
    {
      title: '角色编号',
      dataIndex: 'roleCode',
      key: 'roleCode',
      width: 120,
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
      width: 120,
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
    },
    {
      title: '修改人',
      dataIndex: 'modifier',
      key: 'modifier',
      width: 100,
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      key: 'modifyTime',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个角色吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger size="small">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: Role[]) => {
      console.log('selectedRowKeys:', selectedRowKeys, 'selectedRows:', selectedRows);
    },
  };

  const handleAdd = () => {
    openAddModal();
  };

  const handleEdit = (role: Role) => {
    openEditModal(role);
  };

  const handleDelete = (id: string) => {
    setRoles(roles.filter(role => role.id !== id));
    message.success('删除成功');
  };

  const handleSubmit = async (values: Record<string, unknown>, isAddMode: boolean, currentRecord?: Role | null) => {
    if (isAddMode) {
      // 添加角色
      const newRole: Role = {
        id: Date.now().toString(),
        roleCode: values.roleCode as string,
        roleName: values.roleName as string,
        creator: 'admin',
        createTime: new Date().toISOString().split('T')[0],
        modifier: 'admin',
        modifyTime: new Date().toISOString().split('T')[0]
      };
      setRoles([...roles, newRole]);
      message.success('角色添加成功');
    } else {
      // 编辑角色
      if (currentRecord) {
        setRoles(roles.map(role => 
          role.id === currentRecord.id 
            ? { ...role, ...values }
            : role
        ));
        message.success('角色更新成功');
      }
    }
  };

  const handleSearch = () => {
    // 搜索逻辑
    console.log('搜索:', searchText);
  };

  const handleReset = () => {
    setSearchText('');
  };

  // 过滤数据
  const filteredRoles = roles.filter(role => 
    role.roleName.toLowerCase().includes(searchText.toLowerCase())
  );

  // 分页数据
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedRoles = filteredRoles.slice(startIndex, endIndex);

  return (
    <div style={{ padding: "20px", height: "calc(100vh - 64px)", overflow: "hidden" }}>
      {/* 搜索区域 */}
      <div
        style={{ 
          backgroundColor: "#fff",
          padding: "20px", 
          marginBottom: "20px",
          borderRadius: "4px"
        }}
      >
        <Input
          placeholder="请输入角色名称"
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          style={{ width: 200, marginRight: "auto" }}
          suffix={<SearchOutlined />}
        />
        <Button
          type="primary"
          style={{ marginRight: 8 }}
          onClick={handleSearch}
        >
          搜索
        </Button>
        <Button onClick={handleReset}>重置</Button>
      </div>

      {/* 按钮区域 */}
      <div style={{ marginBottom: "24px", display: "flex" }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          添加角色
        </Button>
      </div>

      {/* 表格区域 */}
      <Table
        columns={columns}
        dataSource={paginatedRoles}
        rowKey="id"
        rowSelection={rowSelection}
        bordered
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: filteredRoles.length,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => 
            `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          onChange: (page, size) => {
            setCurrentPage(page);
            setPageSize(size || 10);
          },
          onShowSizeChange: (current, size) => {
            setCurrentPage(1);
            setPageSize(size);
          },
          pageSizeOptions: ['10', '20', '50', '100'],
        }}
        scroll={{ x: 800, y: "calc(100vh - 500px)" }}
        />

      <CommonFormModal
        visible={visible}
        title={isAddMode ? "添加角色" : "编辑角色"}
        isAddMode={isAddMode}
        currentRecord={currentRecord}
        formItems={permissionFormConfig}
        onSubmit={handleSubmit}
        onCancel={closeModal}
        loading={loading}
        width={600}
      />
    </div>
  );
};

export default Permission;